  <template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="订单编号" prop="id">
          <el-input v-model="queryParams.id" placeholder="请输入订单编号" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="订单类型" prop="ordertype">
          <el-select v-model="queryParams.ordertype" placeholder="请选择订单类型" clearable style="width: 150px;">
            <el-option v-for="dict in doctor_order_type" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="患者id" prop="patientId">
          <el-input v-model="queryParams.patientId" placeholder="请输入患者id" clearable @keyup.enter="handleQuery" />
        </el-form-item> -->
        <el-form-item label="创建时间" style="width: 308px">
          <el-date-picker v-model="daterangeCreateTime" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
            start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <!-- <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['jy:money:add']">新增</el-button>
        </el-col> -->
        <!-- <el-col :span="1.5">
          <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
            v-hasPermi="['jy:money:edit']">修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
            v-hasPermi="['jy:money:remove']">删除</el-button>
        </el-col> -->
        <el-col :span="1.5">
          <el-button type="warning" plain icon="Download" @click="handleExport"
            v-hasPermi="['jy:money:export']">导出</el-button>
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <!-- 收入统计 -->
      <div class="total-income">
        <div class="income-item">
          <span class="label">应收金额（元）</span>
          <span class="amount">{{ (statistics.originalAmount/0.95).toFixed(3) }}</span>
        </div>
        <div class="income-item">
          <span class="label">实收金额（元）</span>
          <!-- <span class="amount">{{ statistics.totalAmount || '0.000' }}</span> -->
          <span class="amount">{{ (statistics.originalAmount)}}</span>
        </div>
      </div>

      <el-table v-loading="loading" :data="moneyList" @selection-change="handleSelectionChange">
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column label="订单编号" align="center" prop="id" />
        <el-table-column label="订单类型" align="center" prop="ordertype">
          <template #default="scope">
            <dict-tag :options="doctor_order_type" :value="scope.row.ordertype" />
          </template>
        </el-table-column>
        <el-table-column label="姓名" align="center" prop="patientInfo.name" />
        <!-- <el-table-column label="性别" align="center" prop="patientInfo.sex">
          <template #default="scope">
            <span v-if="scope.row.patientInfo && scope.row.patientInfo.sex != null">
              <dict-tag :options="sys_user_sex" :value="scope.row.patientInfo.sex" />
            </span>
          </template>
        </el-table-column> -->
        <!-- <el-table-column label="年龄" align="center" prop="patientInfo.age" />
        <el-table-column label="手机号码" align="center" prop="patientInfo.phone" /> -->
        <el-table-column label="科室" align="center" prop="doctorInfo.dept.deptName" />
        <el-table-column label="接诊医生" align="center" prop="doctorInfo.nickName" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="应收金额" align="center">
          <template #default="scope">
            <!-- <span>{{ scope.row.totalcost }} 元</span> -->
            <span>{{ (scope.row.originalAmount || scope.row.totalcost).toFixed(2) }} 元</span>
          </template>
        </el-table-column>
        <el-table-column label="实收金额" align="center">
          <template #default="scope">
            <span>{{ scope.row.totalcost  }} 元</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['jy:money:edit']">修改</el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
              v-hasPermi="['jy:money:remove']">删除</el-button>
          </template>
        </el-table-column> -->
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />

      <!-- 添加或修改订单收费对话框 -->
      <el-dialog :title="title" v-model="open" width="500px" append-to-body>
        <el-form ref="moneyRef" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="订单类型" prop="ordertype">
            <el-select v-model="form.ordertype" placeholder="请选择订单类型">
              <el-option v-for="dict in doctor_order_type" :key="dict.value" :label="dict.label"
                :value="parseInt(dict.value)"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="医生id" prop="doctorId">
            <el-input v-model="form.doctorId" placeholder="请输入医生id" />
          </el-form-item>
          <el-form-item label="患者id" prop="patientId">
            <el-input v-model="form.patientId" placeholder="请输入患者id" />
          </el-form-item>
          <el-form-item label="应收金额" prop="totalcost">
            <el-input v-model="form.totalcost" placeholder="请输入应收金额" />
          </el-form-item>
          <el-form-item label="处方id" prop="prescriptionId">
            <el-input v-model="form.prescriptionId" placeholder="请输入处方id" />
          </el-form-item>
          <el-form-item label="收费人员" prop="tollcollector">
            <el-input v-model="form.tollcollector" placeholder="请输入收费人员" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </template>

<script setup name="Money">
import { listMoney, getMoney, delMoney, addMoney, updateMoney } from "@/api/jy/money";
import { getSumMoney } from "@/api/chy/dingdan";
import { listUser } from "@/api/system/user";
import { listPatient } from "@/api/chy/patient";
import { onMounted, ref } from 'vue';

// 定义数据加载状态
const isDataLoaded = ref(false);

const { proxy } = getCurrentInstance();
const { doctor_order_type, sys_user_sex } = proxy.useDict('doctor_order_type', 'sys_user_sex');

const moneyList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeCreateTime = ref([]);

//定义doctorInfo，用于存储医生信息
const doctorInfo = ref([]);

//定义patientInfo，用于存储患者信息
const patientInfo = ref([]);

// 统计数据
const statistics = ref({
  totalAmount: '0.000',
  originalAmount: '0.000',
  receivableAmount: '0.000',
  discountAmount: '0.000',
  actualAmount: '0.000',
  medicalAmount: '0.000',
  memberAmount: '0.000',
  cashAmount: '0.000',
  alipayAmount: '0.000',
  wechatAmount: '0.000',
  bankAmount: '0.000'
})

function getPatientInfo() {
  return listPatient().then(response => {
    patientInfo.value = response.rows;
  });
}

function getDoctorInfo() {
  return listUser().then(response => {
    doctorInfo.value = response.rows;
  });
}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    id: null,
    ordertype: null,
    patientId: null,
    createTime: null,
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询订单收费列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeCreateTime && '' != daterangeCreateTime) {
    queryParams.value.params["beginCreateTime"] = daterangeCreateTime.value[0];
    queryParams.value.params["endCreateTime"] = daterangeCreateTime.value[1];
  }
  getStatistics().then(() => {
    listMoney(queryParams.value).then(response => {
      const orders = response.rows;
      
      orders.forEach(order => {
        const patient = patientInfo.value.find(p => p.id === order.patientId);
        order.patientInfo = patient || {};
        const doctor = doctorInfo.value.find(d => d.userId === order.doctorId);
        order.doctorInfo = doctor || {};
        
        // 根据vipType判断是否是会员，计算应收金额和实收金额
        if (patient?.vipType === 0) {
          // 非会员：应收金额和实收金额相同
          order.originalAmount = order.totalcost;
          order.totalcost = order.totalcost;
        } else {
          // 会员：实收金额打95折，应收金额 = 实收金额 / 0.95
          order.totalcost = order.totalcost;
          order.originalAmount = order.totalcost / 0.95;
        }
      });
      
      moneyList.value = orders;
      total.value = response.total;
    });
  }).finally(() => {
    loading.value = false;
  });
}

// 获取统计数据
const getStatistics = async () => {
  try {
    const res = await getSumMoney()
    if (res.code === 200) {
      // 计算所有数据的应收金额和实收金额
      let totalOriginalAmount = 0;   // 应收金额
      let totalActualAmount = 0;     // 实收金额
      
      // 获取所有订单数据
      const allOrders = await listMoney({ pageSize: 10000 }); // 设置一个较大的pageSize以获取所有数据
      const orders = allOrders.rows;
      
      orders.forEach(order => {
        const patient = patientInfo.value.find(p => p.id === order.patientId);
        
        // 根据vipType判断是否是会员，计算应收金额和实收金额
        if (patient?.vipType === 0) {
          // 非会员：应收金额和实收金额相同
          totalOriginalAmount += order.totalcost;
          totalActualAmount += order.totalcost;
        } else {
          // 会员：实收金额打95折，应收金额 = 实收金额 / 0.95
          const actualAmount = order.totalcost;
          const originalAmount = order.totalcost / 0.95;
          totalOriginalAmount += originalAmount;
          totalActualAmount += actualAmount;
        }
      });
      
      statistics.value.originalAmount = totalOriginalAmount.toFixed(3);
      statistics.value.totalAmount = totalActualAmount.toFixed(3);
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
    statistics.value.originalAmount = '0.000'
    statistics.value.totalAmount = '0.000'
  }
}


// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    ordertype: null,
    doctorId: null,
    patientId: null,
    totalcost: null,
    prescriptionId: null,
    tollcollector: null,
    createTime: null,
    del: null
  };
  proxy.resetForm("moneyRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeCreateTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加订单收费";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getMoney(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改订单收费";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["moneyRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateMoney(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addMoney(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除订单收费编号为"' + _ids + '"的数据项？').then(function () {
    return delMoney(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('jy/money/export', {
    ...queryParams.value
  }, `money_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  Promise.all([getPatientInfo(), getDoctorInfo()]).then(() => {
    isDataLoaded.value = true;
    // 可选：在数据加载完成后立即调用 getList
    getList();
  }).catch(error => {
    console.error('加载数据失败:', error);
  });
});
</script>

<style lang="scss" scoped>
.total-income {
  background-color: #fffbf4;
  padding: 15px 20px;
  margin-bottom: 20px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 20px;

  .income-item {
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .label {
    font-size: 14px;
    color: #606266;
  }

  .amount {
    font-size: 24px;
    font-weight: bold;
    color: #f5a623;
  }
}
</style>
